<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

//定义支付接口
interface Pay
{
    public function payment();
}
//支付宝支付
class AliPay implements Pay
{
    public $a;
    public $b;
    public function __construct(Wxpay $wx)
    {
    }
    public function payment()
    {
        // TODO: Implement payment() method. 待定事项
        echo '我是支付宝支付';
    }
}
//微信支付
class Wxpay implements Pay
{
    public $a;
    public function __construct()
    {
        $this->a = 1;
    }

    public function payment()
    {
        // TODO: Implement payment() method.   paypal
        echo '我是微信支付';
    }
}
class Order
{
    protected $pay;
    public function __construct(Pay $pay)
    {
        $this->pay = $pay;
    }
    public function success()
    {
        echo '支付成功';
        $this->pay->payment();
    }
}
class  Ioc
{
    public $bindings = [];
    //绑定关系
    public function bind($abstract, $concrete)
    {


        if (!$concrete instanceof Closure)
        {
            $concrete = function ($ioc) use ($concrete) {
                //通过容器的放射类拿到对象
                return $ioc->build($concrete);
            };
        }
        $this->bindings[$abstract]['concrete'] =  $concrete;


    }
    //取出对象
    public function make($abstract)
    {
        $abs = explode("\\",$abstract);
        if(count($abs)>1){
            $abstract = strtolower($abs[count($abs)-1]);
        }else{
            $abstract = strtolower($abstract);
        }

        // 更加key获取bindings的值

        $concrete = $this->bindings[$abstract]['concrete'];
        return $concrete($this);
    }
    //创建对象
    public function build($concrete)
    {
        $reflector = new \ReflectionClass("App\Models\\".$concrete);
        $constructor = $reflector->getConstructor();
        if (is_null($constructor))
        {
            return $reflector->newInstance();
        }else {
            $dependencies = $constructor->getParameters();
            $instances = $this->getDependencies($dependencies);
            return $reflector->newInstanceArgs($instances);
        }
    }
    protected function getDependencies($paramters) {
        $dependencies =  [];
        foreach ($paramters as $paramter) {
            $dependencies[] = $this->make($paramter->getClass()->name);
        }
        return $dependencies;
    }
}
